<?php

namespace App\Http\Controllers\School;

use App\Http\Requests\School\StoreImportUser;
use App\Models\SchoolAdminLog;
use App\Models\SchoolRule;
use App\Models\User;

/**
 * Class ImportUserController
 * @package App\Http\Controllers\School
 * 学校后台批量导入用户数据
 */
class ImportUserController extends BaseController
{
    /**
     * @param StoreImportUser $request
     * @return array
     * 批量导入用户数据
     */
    public function store(StoreImportUser $request)
    {
        $failPhones = [];       // 失败记录的手机号
        $failCount = 0;         // 失败的记录条数
        $schoolRule = SchoolRule::where('school_id', \Auth::user()->school_id)->first();
        foreach ($request->users as $item) {
            // 若对应的键值不为空 && 整个users表中不存在相同手机号码 && 手机号格式正确
            if (isset($item['name']) && isset($item['phone']) && User::query()->where('phone', $item['phone'])->doesntExist() && preg_match("/^1[345789]\d{9}$/", $item['phone'])) {
                $user = new User();
                $user->school_id = \Auth::user()->school_id;
                $user->role_id = $request->role;
                $user->name = $item['name'];
                $user->phone = $item['phone'];
                $user->source_from = 'import';
                $user->morning_rule = $schoolRule->morning_rule;
                $user->lunch_rule = $schoolRule->lunch_rule;
                $user->dinner_rule = $schoolRule->dinner_rule;
                if ($user->save()) {
                    continue;
                }
            }
            $failCount++;
            if (isset($item['phone'])) {
                array_push($failPhones, $item['phone']);
            }
        }
        SchoolAdminLog::log('批量导入用户');
        return [
            'count' => count($request->users),
            'failed' => $failCount,
            'failedPhones' => $failPhones
        ];
    }
}
